package com.lyc.user.serlvet;

import com.lyc.user.bean.User;
import com.lyc.user.servceImpl.UserServiceImpl;
import com.lyc.user.service.UserService;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class UserAccountLogin implements Servlet{
	private ServletConfig servletConfig;
  public UserAccountLogin() {
	
  }
	@Override
	public void destroy() {
		
	}

	@Override
	public ServletConfig getServletConfig() {
		return servletConfig;
	}

	@Override
	public String getServletInfo() {
		return null;
	}

	@Override
	public void init(ServletConfig config) throws ServletException {
		this.servletConfig=config;
	}

	@Override
	public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
	
				String account = req.getParameter("account");
				String pwd  =req.getParameter("pwd");

//		String nickName = req.getParameter("nickName");
		User user = new User();
				user.setAccount(account);
				user.setPwd(pwd);
//				user.setNickName(nickName);
				UserService userService = new UserServiceImpl();

//		获得http请求中的信息，所以需要把SeveltRequest对象强转为HttpServletRequest对象
		 HttpServletResponse resp=(HttpServletResponse)res;
		HttpServletRequest request=(HttpServletRequest) req;
//		System.out.println("getContextPath："+request.getContextPath());//发布工程名
//		System.out.println("getQueryString："+request.getQueryString());//获得请求地址?之后的内容。
//		System.out.println("getRequestURI："+request.getRequestURI());//发布工程名+资源的地址
//		System.out.println("getServletPath："+request.getServletPath());//资源的地址

		resp.setCharacterEncoding("UTF-8");
		 resp.setContentType("text/html");
		User u = userService.accountLogin(user);

		//		请求的重定向
		if(u==null){
			//  getServletContext() 获得：http://localhost:端口名
			//  getContextPath() 获得工程名 javaWeb01
            //重定向
			resp.sendRedirect(req.getServletContext().getContextPath()+"/html/login.jsp");
		}else if (!(u.getPwd().equals(pwd))){
			resp.sendRedirect(req.getServletContext().getContextPath()+"/html/login.jsp");
		}else{
			request.getSession().setAttribute("userAccount",u);

			//创建Cookie对象
			Cookie accountCookie = new Cookie("accountCookie",account);
			//设置accountCookie的存活时间（10天）
			accountCookie.setMaxAge(60*60*24*10);
			//设置accountCookie的作用路径
			accountCookie.setPath("/");
			//把accountCookie添加到响应中
			resp.addCookie(accountCookie);

			//判断是否10天免登录
			String mianLogin = request.getParameter("mianLogin");
			if (mianLogin!=null){
				Cookie pwdCookie = new Cookie("pwdCookie", pwd);
				pwdCookie.setMaxAge(60*60*24*10);
				pwdCookie.setPath("/");
				resp.addCookie(pwdCookie);
			}
//		    resp.sendRedirect(req.getServletContext().getContextPath()+"/bookServlet?methodName=getBookList");
			resp.sendRedirect(req.getServletContext().getContextPath()+"/bookServlet?methodName=getBookPageList");

		}
	}
}
